// 增删改查的操作
import { AddUserModel } from "@/api/user/userModel"
import { Result } from "@/http/request"
import { EditType } from "@/type/BaseEnum"
import { ref } from "vue"
import { addUserApi, editUserApi, deleteUserApi } from "@/api/user/user"
import userInstance from '@/hooks/userInstance'
export default function curd(getUserList) {
    // 全局属性
    const {global} = userInstance()

    // 新增弹框ref属性
    const addRef = ref<{ show:(type:string,row?:AddUserModel) => void }>()
    // 分配角色ref属性
    const assignRef = ref<{ show:(name: string, userId: string | number) => void }>()

    // 搜索
    const searchBtn = () => {
        getUserList()
    }

    // 新增
    const addBtn = () => {
        // 显示弹窗
        addRef.value?.show(EditType.ADD)
    }
    // 编辑
    const editBtn = (row:AddUserModel) => {
        // 显示弹窗
        addRef.value?.show(EditType.EDIT,row)
    }
    // 删除
    const deleteBtn = async (id: number) => {
        let params = {
            id: id
        }
        let confirm = await global.$myConfirm('确定删除该数据吗?')
        if(confirm) {
            let res = await deleteUserApi(params)
             if(res && res.code === 200) {
                global.$message({
                    message: res.msg,
                    type: 'success'
                })
                getUserList()
            }
        }
       
    }
    // 分配角色
    const assignBtn = (name:string, id: string | number) => {
        // 显示弹窗
        assignRef.value?.show(name, id)
    }
    // 新增/编辑保存
    const save = async (params: AddUserModel) => {
        console.log('父组件接收到参数===', params)
        let res : Result
        if(params.type === EditType.ADD) {
            res = await addUserApi(params)

        } else {
            res = await editUserApi(params)
        }
        if(res && res.code === 200) {
            // 刷新列表
            getUserList()
            // 信息提示
            global.$message({
                message: res.msg,
                type: 'success'
            })
        }
    }
    return {
        searchBtn,
        addBtn,
        editBtn,
        deleteBtn,
        assignBtn,
        addRef,
        assignRef,
        save
    }
}